package com.security.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SmsCodeAuthenticationProvider implements AuthenticationProvider{
	
	private UserDetailsService userDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken)authentication;
		UserDetails user = userDetailsService.loadUserByUsername((String)smsCodeAuthenticationToken.getPrincipal());
		if (user == null) {
			throw new InternalAuthenticationServiceException("无法获取用户信息");
		}
		return createSuccessAuthentication(smsCodeAuthenticationToken.getPrincipal(), smsCodeAuthenticationToken);
	}
	
	/**
	 * @title createSuccessAuthentication
	 * @description 创建成功的验证
	 * @author Dark_blue
	 * @date 2019年11月7日
	 * @param principal
	 * @param authentication
	 * @return
	 */
	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication) {
		UserDetails user = userDetailsService.loadUserByUsername((String)principal);
		SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(principal, user.getAuthorities());
		result.setDetails(authentication.getDetails());
		return result;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}

	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

}
